package com.dogstudio.mygame.ui;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.dogstudio.mygame.R;
import com.dogstudio.mygame.config.Config;
import com.dogstudio.mygame.view.GamePanel;
import com.dogstudio.mygame.view.ResultDialog;


public class AndroidGameActivity extends Activity implements GamePanel.OnChangeListener {
    private TextView mTvScore;
    private TextView mTvBestScore;
    private Button mBtnNewGame;
    private GamePanel mGamePanel;
    private ResultDialog mDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_android_game);
        initViews();
        initData();
    }

    private void initViews() {
        mTvScore = (TextView) findViewById(R.id.tv_current_score);
        mTvBestScore = (TextView) findViewById(R.id.tv_best_score);
        mBtnNewGame = (Button) findViewById(R.id.btn_new_game);
        mBtnNewGame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startNewGame();
            }
        });
        mGamePanel = (GamePanel) findViewById(R.id.game_panel);
        mGamePanel.setOnChangeListener(this);
    }

    private void initData() {
        startNewGame();
    }

    @Override
    public void onBackPressed() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
            return;
        }

        super.onBackPressed();
    }

    private void setCurrentScore(int score) {
        mTvScore.setText("SCORE\n" + score);
    }

    private void setBestScore(int score) {
        mTvBestScore.setText("BEST\n" + score);
    }


    private void startNewGame() {
        setCurrentScore(0);
        setBestScore(Config.getBestScore(this));
        mGamePanel.restartGame();
    }


    @Override
    public void onChange() {
        setCurrentScore(mGamePanel.getScore());
    }

    @Override
    public void onGameOver(boolean isSuccess) {
        if (mDialog == null) {
            mDialog = new ResultDialog(AndroidGameActivity.this, new ResultDialog.OnOkListener() {
                @Override
                public void onOk() {
                    startNewGame();
                }

                @Override
                public void onCancel() {
                    finish();
                }
            });
        }
        if (isSuccess) {
            mDialog.setMsg("游戏闯关成功", "是否再来一局？");
        } else {
            mDialog.setMsg("游戏闯关失败", "是否再来一局？");
        }
        mDialog.show();
    }
}
